<?php

namespace app\jigou\controller\qingdongams\jigoucustomer;

use addons\qingdongams\model\Customer;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\Quote as QuoteModel;
use addons\qingdongams\model\QuoteFile;
use addons\qingdongams\model\QuoteOther;
use addons\qingdongams\model\QuoteProduct;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;

/**
 * 报价单管理
 * @icon fa fa-user
 */
class Quote extends Base
{
    protected $relationSearch = true;
    protected $searchFields = 'id,number';
    /**
     * @var \addons\qingdongams\model\Quote
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new QuoteModel;
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $createtime = input('createtime', '');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = [];
            if ($createtime && $createtime != 'null ') {
                $start = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y")));
                $end = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("t"), date("Y")));
                $wheres['createtime'] = array('between', array(strtotime($start), strtotime($end)));
            }
            $whereFlow = function ($query) {
                $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                    ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_id)");
            };
            $list = $this->model->where($where)->where($wheres)->where($whereFlow)->with(['ownerStaff', 'customer', 'contacts'])->order($sort, $order)->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加报价单
     */
    public function add()
    {

        if ($this->request->isPost()) {
            //移除HTML标签
            $this->request->filter('trim');
            $params = $this->request->post('row/a');

            if (!isset($params['product']) || !$params['product'] || $params['product'] == '[]') {
                $this->error('请选择产品');
            }

            // 表单验证
            if (($result = $this->validate($params, 'addons\qingdongams\validate\Quote.create')) !== true) {
                $this->error($result);
            }
            if(isset($params['flow_staff_ids'])  && $params['is_check']==1){
                if(!$params['flow_staff_ids']){
                    $this->error('请选择审批人');
                }
            }
            $params['product'] = json_decode($params['product'], true);
            foreach ($params['product'] as $v) {
                if (empty($v['product_id'])) {
                    $this->error('产品名称不能为空');
                }
                if (empty($v['price'])) {
                    $this->error('产品单价不能为空');
                }
                if (empty($v['number'])) {
                    $this->error('产品数量不能为空');
                }
            }
            try {
                $result = QuoteModel::createQuote($params);
                $customerModel = new Customer();
                $customerInfo = $customerModel->where(['id' => $params['customer_id']])->find();
                if (!in_array($customerInfo['follow'], ['准备购买', '准备付款', '已经购买'])) {
                    $customerModel->where(['id' => $params['customer_id']])->update(['follow' => '准备购买']);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('新增报价单成功');
            }
            $this->error('新建报价单失败');
        }
        $clause = "· 交货期：订单生效后，5个、10个、15个、25个、30工作日内发货。<br>
· 交货地点：贵司工厂（仅限大陆工厂）/客户提供指定安装地点<br>
· 保修期：12个月或24个月<br>
· 有效期：30天、60天、90天。<br>
· 付款方式：全款发货/五五/三六一。<br>
· 含税方式：不含税/含13%增值税。";

        $flow = Flow::getsteplist(Flow::QUOTE_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }

        $this->assign('flow', $flow);
        $customer_id = input('customer_id');
        $this->assign('customer_id', $customer_id);
        $this->view->assign('clause', $clause);
        $this->view->assign('number', getItemNumber('quote'));
        $this->view->assign('customer', Customer::getList());
        return $this->view->fetch();
    }

    /**
     * 修改报价单
     */
    public function edit($ids = null)
    {
        $map['id'] = $ids;

        if ($this->request->isPost()) {
            //移除HTML标签
            $this->request->filter('trim');
            $params = $this->request->post('row/a');
            $row = QuoteModel::where(['id' => $ids])->find();
            if (empty($row)) {
                $this->error('修改报价单信息不存在');
            }
            if (!isset($params['product']) || !$params['product'] || $params['product'] == '[]') {
                $this->error('请选择产品');
            }
            $params['product'] = json_decode($params['product'], true);
            foreach ($params['product'] as $v) {
                if (empty($v['product_id'])) {
                    $this->error('产品名称不能为空');
                }
                if (empty($v['price'])) {
                    $this->error('产品单价不能为空');
                }
                if (empty($v['number'])) {
                    $this->error('产品数量不能为空');
                }
            }
            // 表单验证
            if (($result = $this->validate($params, 'addons\qingdongams\validate\Quote.create')) !== true) {
                $this->error($result);
            }
            Db::startTrans();
            try {
                $params['id'] = $ids;
                $params['status'] = 0;
                QuoteModel::updateQuote($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改报价单信息成功');

        }

        $flow = Flow::getsteplist(Flow::QUOTE_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }

        $this->assign('flow', $flow);
        $row = $this->model->with(['product', 'customer', 'contacts'])->where($map)->find();
        $row = $row->toArray();
        $row = QuoteOther::getOther($row);
        $this->view->assign("row", $row);
        $this->view->assign('customer', Customer::getList());
        return $this->view->fetch();
    }

    /**
     * 报价单详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['createStaff', 'ownerStaff', 'customer', 'contacts', 'orderStaff'])->where([
            'id' => $ids,
        ])->find();

        $row = $row->toArray();
        $row = QuoteOther::getOther($row);

        if ($row['check_status'] == 0 || $row['check_status'] == 1) {
            $row['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::QUOTE_TYPE, $ids);
        } else {
            $row['is_examine'] = 0;
        }
        Message::setRead(Message::QUOTE_TYPE, $ids, $this->_staff->id);
        $product = QuoteProduct::where(['quote_id' => $ids])->with(['product'])->select();

        $this->assign('flow', Flow::getstepdetail(Flow::QUOTE_STATUS, $ids));
        $this->assign('examine_record', ExamineRecord::getList(ExamineRecord::QUOTE_TYPE, $ids));

        $this->assign('product', $product);
        $this->assign('row', $row);
        $this->assign('ids', $ids);

        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    /**
     * 获取附件记录
     */
    public function get_file($ids = null)
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongams\model\QuoteFile::where(['quote_id' => $ids])->with(['file', 'auth'])->field('file_id,createtime,create_id')->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 添加附件记录
     */
    public function img($ids = null)
    {
        $map['id'] = $ids;
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try {
                QuoteFile::addFiles($params['fild_ids'], $ids, $this->_staff->id);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('成功');
        }
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 删除文件
     */
    public function del_file($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $map['file_id'] = $ids;
        $result = QuoteFile::where($map)->delete();
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    /**
     * 作废报价单
     */
    public function tovoid_quote()
    {
        $id = input('id');
        $row = QuoteModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('报价单信息不存在');
        }

        try {
            $result = QuoteModel::where(['id' => $id])->update(['status' => 9, 'check_status' => 9]);

            ExamineRecord::cancelExaminse(ExamineRecord::QUOTE_TYPE, $id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('作废报价单成功');
        }
        $this->error('作废失败');
    }

    /**
     * 下载报价单
     */
    public function download_quote($id = null)
    {
        $quote = QuoteModel::withTrashed()->where(['id' => $id])
            ->with(['customer', 'contacts', 'orderStaff'])->find();
        if (empty($quote)) {
            $this->error('报价单不存在');
        }

        $quote = $quote->toArray();
        $quoteProduct = QuoteProduct::where(['quote_id' => $id])->with(['product'])->select();
        $product_type = json_decode($quote['product_type'], true);
        $product_type_name = [];
        foreach ($product_type as $t) {
            $product_type_name[] = $t['name'] ?? '';
        }
        $product_type_name = implode(',', $product_type_name);
        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/baojia1.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);

        $tmp->setValue('product_type', $product_type_name);//替换变量name
        //对齐变量
        $name = $quote['customer']['name'] ?? '';
        $name = $name . @str_repeat('　', 13 - mb_strlen($name));
        $address = $quote['customer']['address'] ?? '';
        $address = $address . @str_repeat('　', 13 - mb_strlen($address));
        $contacts = $quote['contacts']['name'] ?? '';
        $contacts = $contacts . @str_repeat('　', 13 - mb_strlen($contacts));
        $mobile = $quote['contacts']['mobile'] ?? '';
        $mobile = $mobile . @str_repeat('　', 13 - ceil(mb_strlen($mobile) / 2));
        $order_contacts = $quote['order_staff']['name'] ?? '';
        $order_mobile = $quote['order_staff']['mobile'] ?? '';
        $tmp->setValue('name', $name);//替换变量name
        $tmp->setValue('address', $address);//替换变量address
        $tmp->setValue('contacts', $contacts);//替换变量contacts
        $tmp->setValue('mobile', $mobile);//替换变量mobile
        $tmp->setValue('order_contacts', $order_contacts);
        $tmp->setValue('order_mobile', $order_mobile);
        $tmp->setValue('price', $quote['quote_amount']);
        $tmp->setValue('price_big', convertAmountToCn($quote['quote_amount']));//替换变量mobile
        $rows = count($quoteProduct);//总行数
        $tmp->cloneRow('num', $rows);//复制行
        $content = '';

        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("num#" . ($i + 1), $i + 1);//序号
            $tmp->setValue("one#" . ($i + 1), $quoteProduct[$i]['name'] ?? '');//名称
            $tmp->setValue("two#" . ($i + 1), $quoteProduct[$i]['product_type']['name'] ?? '');//规格/说明
            $tmp->setValue("three#" . ($i + 1), $quoteProduct[$i]['config_desc'] ?? '');//配置说明
            $tmp->setValue("four#" . ($i + 1), $quoteProduct[$i]['number'] ?? '');//数量
            $tmp->setValue("five#" . ($i + 1), $quoteProduct[$i]['unit'] ?? '');//单位
            $tmp->setValue("sex#" . ($i + 1), $quoteProduct[$i]['unit_price'] ?? '');//单价
            $tmp->setValue("eight#" . ($i + 1), $quoteProduct[$i]['price'] ?? '');//总价
            $tmp->setValue("remarks#" . ($i + 1), $quoteProduct[$i]['remarks'] ?? '');//备注

            $content .= "<br>" . $quoteProduct[$i]['description'] ?? '';
        }
        //start 配置
        $configs = [];
        foreach ($quoteProduct as $v) {
            if ($v['config']) {
                $pconfig = [];
                foreach ($v['config'] as $vrc) {
                    $vrc['num'] = $vrc['num'] ?? 0 * $v['number'] ?? 0;
                    $pconfig[] = $vrc;
                }
                $configs = array_merge($configs, $pconfig);
            }
        }
        $tmp->cloneRow('i', count($configs));//复制行
        $block = [];
        foreach ($configs as $k => $ves) {
            $block['i#' . ($k + 1)] = $k + 1;
            $block['cname#' . ($k + 1)] = $ves['name'];
            $block['cnum#' . ($k + 1)] = $ves['num'];
            $block['cremark#' . ($k + 1)] = $ves['remark'];
        }
        $tmp->cloneBlock('config', 1, true, false, [$block]);

        //end 配置

        //start 特约条款
        $clause = strip_tags(html_entity_decode($quote['clause']));
        $clause = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($clause)); //去除空格和换行
        $clauseList = explode('·', $clause);
        $replacements = [];
        foreach ($clauseList as $v) {
            if ($v) {
                $replacements[] = ['clause' => $v];
            }
        }
        $tmp->cloneBlock('clauseBlock', 0, true, false, $replacements);
        //end 特约条款
        $showNames = [];
        foreach ($quoteProduct as $v) {
            $showNames[] = $v['name'];
        }
        $products = \addons\qingdongams\model\Product::where([])->order('id asc')->column('name');
        foreach ($products as $v) {
            if (in_array($v, $showNames)) {
                //显示
                $tmp->cloneBlock($v);
            } else {
                $tmp->cloneBlock($v, 0);
            }
        }
        $filename = $quote['customer']['name'] . date('YmdHis') . '.docx';
        $fileurl = './docx/' . date('Ymd') . '/';

        if (!file_exists('./docx/')) {
            mkdir('./docx/');
        }
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new \addons\qingdongams\model\File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();

        $file = cdnurl($model::getUrl($lastid), true);
        $data = ['file' => $file, 'id' => $lastid, 'filename' => $filename];
        $this->success('成功', '', $data);;
    }

}
